package com.aischool.interceptor;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;

import com.aischool.service.AuthService;
import com.aischool.service.SysUserService;
import com.aischool.utils.AppUtil;
import com.aischool.utils.JsonCodeEnum;
import com.aischool.utils.JsonResult;
import com.aischool.utils.JwtToken;
import com.aischool.utils.SysAppEnum;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

public class PermissionInterceptor implements Interceptor {
	
	@Inject
	SysUserService sysUserService;
	@Inject 
	AuthService authService;
	
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		
		if (!checkPower(controller)) {
			return;
		}
		
		inv.invoke();
	}
	
	public boolean checkPower(Controller controller) {
		
		HttpServletRequest request = controller.getRequest();
        //HttpServletResponse response = controller.getResponse();
        
        //AppUtil.getSiteDomain(request);
        //AppUtil.getSiteHost(request);
        
        String surl = request.getRequestURI().toString();
        String contextPath = request.getContextPath();
        surl = surl.substring(contextPath.length());
        
        String request_accept = request.getHeader("Accept");
        //System.err.println(request_accept);
        
        boolean is_admin_url = surl.startsWith("/admin/") && surl.indexOf("eduorg")<0;
        boolean is_api_url = surl.startsWith("/api/") && surl.indexOf("eduorg")<0;
        
        boolean is_eduorg_url = surl.startsWith("/admin/eduorg");
        boolean is_eduorg_api_url = surl.startsWith("/api/eduorg");
        
        boolean is_front_url = surl.startsWith("/front");
        boolean is_family_url = surl.startsWith("/front/family");
        boolean is_teacher_url = surl.startsWith("/front/teacher");
        
        boolean is_token_from_header = false;
        
        int userid = 0; 										//JwtToken.getUserID(sToken);
    	int appid = 0;
    	int orgid = 0;
    	
    	int url_app_id = AppUtil.toInt(AppUtil.getUrlParam(surl, "app_id"), 0);
    	
    	// cookie flag
    	String cookie_flag = "";
    	if (is_teacher_url) { cookie_flag = "_"+SysAppEnum.TEACHER_APP.getId(); }
    	else if (is_family_url) { cookie_flag = "_"+SysAppEnum.FAMILY_APP.getId(); }
    	else if (is_eduorg_url || is_eduorg_api_url) { cookie_flag = "_"+SysAppEnum.EDU_ORG_APP.getId(); }
    	else if (is_admin_url || is_api_url) { cookie_flag = "_"+SysAppEnum.SYS_EDU_APP.getId(); }
    	request.setAttribute("cookie_flag", cookie_flag);
    	
    	System.err.println("cookie_flag:" + AppUtil.getCookieTokenKey(controller));
                
        if(StrKit.isBlank(surl) 
                || surl.startsWith("/upload") 
                || surl.startsWith("/static") 
                || surl.startsWith("/common")
                || StrKit.notBlank(FilenameUtils.getExtension(surl))  
                || surl.startsWith("/api/verify")
                || surl.startsWith("/api/area")
                
                || surl.startsWith("/admin/login")
                || surl.startsWith("/api/auth/login")
                || surl.startsWith("/api/auth/logout")
                
                || surl.startsWith("/admin/eduorg/login")
                || surl.startsWith("/api/eduorg/auth/login")
                || surl.startsWith("/api/eduorg/auth/logout")
                
                || surl.startsWith("/front/family/login")
                || surl.startsWith("/front/family/auth/login")
                || surl.startsWith("/front/family/auth/logout")
                || surl.startsWith("/front/family/register")
                
                || surl.startsWith("/front/teacher/login")
                || surl.startsWith("/front/teacher/auth/login")
                || surl.startsWith("/front/teacher/auth/logout")
                || surl.startsWith("/front/teacher/register")
                || surl.startsWith("/front/teacher/html")
                
                || surl.startsWith("/weixin/")
        		){
        	
            return true;
        }
        
        JsonResult jr = new JsonResult();
    	
    	if (url_app_id <=0) {
	    	if (is_family_url) {
	    		url_app_id = SysAppEnum.FAMILY_APP.getId();
	    	}else if (is_teacher_url) {
	    		url_app_id = SysAppEnum.TEACHER_APP.getId();
	    	}
    	}
    	
    	
        if (is_api_url || is_admin_url || is_eduorg_url || is_eduorg_api_url || is_front_url) { 				
        	// 获取cookie
            String sToken = AppUtil.getCookie(request, AppUtil.getCookieTokenKey(controller));

            // cookie is null, check header
            if (StrKit.isBlank(sToken)) {
            	sToken = controller.getHeader("auth_token");
            	if (!StrKit.isBlank(sToken)) {
            		is_token_from_header = true;
            		System.err.println("header token");
            	}
            }
            
            if (StrKit.isBlank(sToken)) {
            	jr.appendMsg("~");
            }else {
            	// 获取用户 id
            	String tokenVal = JwtToken.getTokenVal(sToken);
            	
            	
            	if (StrKit.notBlank(tokenVal)) {
            		String[] arr1 = tokenVal.split(",");
            		if (arr1.length>=3) {
            			userid = AppUtil.toInt(arr1[0], 0);
            			appid = AppUtil.toInt(arr1[1], 0);
            			orgid = AppUtil.toInt(arr1[2], 0);
            		}
            	}
            		
            	if (userid <= 0 || appid <= 0) {
            		jr.appendMsg(".丢失的认证信息！");
            	}else if (url_app_id>0 && url_app_id != appid) {
            		jr.appendMsg(".您还没有登录，请先登录！");
            		jr.setDicKV("data:", url_app_id + "==" + appid);
            	}else if (appid==4 && orgid <= 0) {
            		jr.appendMsg(".丢失的认证信息！机构数据错误！");
            	}else {
            		// 设置临时变量 - 用户ID
            		request.setAttribute("login_user_id", userid);
            		// 设置临时变量 - 应用ID
            		request.setAttribute("login_app_id", appid);
            		// 设置临时变量 - 机构ID
            		request.setAttribute("login_org_id", orgid);
            		
            		// 获取用户数据
            		Record rduser = sysUserService.getUser(userid);
            		if (rduser == null) {
            			jr.appendMsg(".用户不存在！");
            		}else if (rduser.getInt("user_state") != 1){
            			jr.appendMsg(".用户已禁用！");
            		}else if (rduser.getBoolean("is_lock")){
            			jr.appendMsg(".用户被锁定！");
            		}else if(!authService.checkAppPower(userid, appid)){
            			jr.appendMsg(".您所在的用户组没有应用权限！");
            		}else if(!authService.checkUserPower(userid, appid, surl)){
            			jr.appendMsg(".您所在的用户组没有权限！");
            		}else {
            			// 验证通过
            			
            			// 设置临时变量 - 用户ID
                		request.setAttribute("login_user_name", rduser.getStr("login_name"));
                		request.setAttribute("login_user_record", rduser);
                		
                		if (is_token_from_header) {
                			AppUtil.setCookie(controller.getRequest(), controller.getResponse(), AppUtil.getCookieTokenKey(controller), sToken, AppUtil.Cookie_maxAgeInSeconds);
                		}
            			
            			return true;
            		}
            	}
            }
            
            
        }
        
        // 认证失败, 清除cookie
        controller.removeCookie(AppUtil.getCookieTokenKey(controller));
        
        System.err.println("认证失败");
        jr.setEnum(JsonCodeEnum.Faild_User_NoLogin);
        
        // 机构系统  startWith /admin/eduorg
        if (is_eduorg_url) {
        	String strhtml = "<script type=\"text/javascript\">"
        			+ "alert('"+jr.getMsg()+"');"
        			+ "window.top.location = '/admin/eduorg/login/"+controller.getInt("app_id",0)+"';"
        			+ "</script> ";
        	controller.renderHtml(strhtml);
	        return false;
        }
        // 后台管理系统  startWith /admin/
        if (is_admin_url) {
        	String strhtml = "<script type=\"text/javascript\">"
        			+ "alert('"+jr.getMsg()+"');"
        			+ "window.top.location = '/admin/login/"+controller.getInt("app_id",1)+"';"
        			+ "</script> ";
        	controller.renderHtml(strhtml);
	        return false;
        }
        
        if (!request_accept.equals("application/json")) {
        	if (is_family_url) {
        		String locationhref = "/front/family/login";
            	String strhtml = "<script type=\"text/javascript\">"
            			+ "window.top.location = '"+locationhref+"';"
            			+ "</script> ";
            	controller.renderHtml(strhtml);
    	        return false;
            }
        }
        
        controller.renderJson(jr.Dic);		
		return false;
	}
}
